package com.hzbc.faceattendance.controller;

import com.hzbc.faceattendance.service.IWechatEventService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.IOException;

/**
 * 需要在微信公众号后台配置服务器地址为https://yourdomain.com/wechat/event
 * 确保服务器支持HTTPS（微信公众号接口要求）
 * 实际部署时需要将getToken()方法中的硬编码替换为从SystemConfig获取
 */

@Slf4j
@RestController
@RequestMapping("/wechat/event")
public class WechatEventController {

    @Autowired
    private IWechatEventService wechatEventService;

    /**
     * 微信服务器验证接口
     */
    @GetMapping
    public void verifyServer(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        if (wechatEventService.checkSignature(signature, timestamp, nonce)) {
            response.getWriter().print(echostr);
        } else {
            response.getWriter().print("Invalid signature");
        }
    }

    /**
     * 接收微信事件推送
     */
    @PostMapping(produces = "application/xml;charset=UTF-8")
    public String handleEvent(HttpServletRequest request) {
        try {
            return wechatEventService.processEvent(request);
        } catch (Exception e) {
            log.error("处理微信事件异常", e);
            return "success";
        }
    }
}